<?php
/*pipahr
 *chinwin copyright
 *2013-09-03
*/

class PCalendarHelper
{
   // Offer feedback status
   const OFFER_FEEDBACKSTATUS_ACCEPTED = 1;  //接受offer
   const OFFER_FEEDBACKSTATUS_REJECTED = 2; //拒绝offer
   const OFFER_FEEDBACKSTATUS_ENTRY = 3;  //入职

   // Jobseeker status
   const JOBSEEKER_STATUS_NOENTRY = 410; //未入职
   const JOBSEEKER_STATUS_PROBATION = 420; //试用期
   const JOBSEEKER_STATUS_POSITIVE = 430;//转正
   const JOBSEEKER_STATUS_DISMISS = 440;//辞退
   const JOBSEEKER_STATUS_VOLUNTARY_TURNOVER = 450;//主动离职
   const JOBSEEKER_STATUS_SENDED = 310;  //已发offer
   const JOBSEEKER_STATUS_ACCEPTED = 320;  //接受offer
   const JOBSEEKER_STATUS_REJECTED = 330; //拒绝offer
   const JOBSEEKER_STATUS_HIRE = 220;  //录用
   const JOBSEEKER_STATUS_NOTHIRE = 230;  //不录用
   const JOBSEEKER_STATUS_RETEST = 240;  //进入复试
   const JOBSEEKER_STATUS_ABSENT = 250;  //面试缺席
   const JOBSEEKER_STATUS_CANCEL = 260;  //面试取消
   const JOBSEEKER_STATUS_INTERVIEW = 210;  //安排面试
   const JOBSEEKER_STATUS_GIVEUP = 140;  //主动放弃

   // These numbers are mapping back to database oc_calendar_result table
   // Interview result status
   const INTERVIEW_RESULT_CANCEL = 5;  //取消
   const INTERVIEW_RESULT_ABSENT= 4;   //缺席
   const INTERVIEW_RESULT_RETEST = 3;  //复试
   const INTERVIEW_RESULT_HIRE = 1;    //录用
   const INTERVIEW_RESULT_NOTHIRE = 2; //不录用
   // Jobseeker reject interivew status
   const INTERVIEW_REJECT = 1; //拒绝
   // Interviewer cancel interivew status
   const INTERVIEW_CANCEL = 1; //取消
   // Entry feedback status
   const ENTRY_FEEDBACKSTATUS_PROBATION = 1; //试用期
   const ENTRY_FEEDBACKSTATUS_POSITIVE = 2; //转正
   const ENTRY_FEEDBACKSTATUS_DISMISS = 3; //辞退
   const ENTRY_FEEDBACKSTATUS_VOLUNTARY_TURNOVER = 4; //主动离职
   const ENTRY_FEEDBACKSTATUS_NOENTRY = 5; //未入职

   //interview form types
   const INTERVIEW_FORM_RESET = 1;//取消这轮面试后的重新安排
   const INTERVIEW_FORM_EDIT = 2; //编辑面试
   const INTERVIEW_FORM_NEW = 3; //安排新面试

   // Interview stat
   const UPDATE_INTERVIEW = 1; //更新面试
   const NEW_INTERVIEW = 2; //新增面试
   const ENTRY_INTERVIEW = 3; //已经进入入职流程
   const OFFER_INTERVIEW = 4; //已经发offer
   const RESET_INTERVIEW = 5; //取消面试后的重新安排

   public static function getListOrder() {
      $app = PFactory::getApplication();
      $calendarlistdir = $app->getUserState('calendarlistdir', array('orderdir'=>'DESC'));
      $orderby = JArrayHelper::getValue($calendarlistdir, 'orderby', 'startdate');
      $orderdir = strtoupper(JArrayHelper::getValue($calendarlistdir, 'orderdir', 'ASC'));
      $listorders = array();
      array_unshift($listorders, $orderby." ".$orderdir);
      return array($listorders);
   }

   // build search url, which carry original url params
   public static function getSearchUrl() {
      $JURI = JURI::getInstance();
      $curPath  = $JURI->toString(array('path'));
      if ($curPath == OC_Helper::linkToRoute('calendar_search')) {
         $searchUrl = $JURI->toString(array('path','query'));
      } else {
      $curQuery = $JURI->toString(array('query'));
         $searchUrl = OC_Helper::linkToRoute('calendar_search') . $curQuery;
      }

      return $searchUrl;
    }

   /**
    * Get sub account displayname by uid (email), if this email haven't registered, return null
    * @param  string $uid email
    * @return string  display name
    */
   public static function getDisplayName($uid){
      $db = PFactory::getDbo();
      $master_user = PFactory::getMasterUser()->id;
      $query = "SELECT displayname FROM *PREFIX*users_extended AS e " .
               " LEFT JOIN *PREFIX*users AS u ON u.uid = e.uid  WHERE e.uid = " . $db->quote($uid) . " AND e.owner = " . $db->quote($master_user);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $displayname = $db->loadResult();
      return $displayname ? $displayname : null;
   }

   /**
    * Check token is valid or not
    * @param  string $token share token
    * @return if valid return objectid else return false
    */
   public static function checkShareToken($token) {
      $db = PFactory::getDbo();
      $query = "SELECT item_source FROM *PREFIX*share WHERE token = ".$db->quote($token);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $shared_obid = $db->loadResult();
      return $shared_obid ? $shared_obid : false;
   }
   
   public static function checkOfferToken($token,$sharewith){
      $db = PFactory::getDbo();
      $query = "SELECT item_source FROM *PREFIX*share WHERE token = ".$db->quote($token)." AND share_with = ".$db->quote($sharewith)." AND item_type='offer'";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $shared_obid = $db->loadResult();
      return $shared_obid ? $shared_obid : false;
   }
   /**
    * Get share event info via token & share email
    * @param  string $token     share token
    * @param  string $sharewith share email or subaccount
    * @return bool
    */
   public static function getShareEvent( $token='', $sharewith='' ) {
      if(empty($token) || empty($sharewith))
         return false;
      $db = PFactory::getDbo();
      $query = "SELECT s.item_source AS objectid, s.share_with AS userid, s.uid_owner, s.token, o.startdate
         FROM *PREFIX*share s
         LEFT JOIN *PREFIX*calendar_objects o ON o.id = s.item_source
         WHERE s.item_type='event' AND s.token=" . $db->quote($token) . ' AND s.share_with=' . $db->quote($sharewith);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $result = $db->loadAssoc();
      return $result ? $result : false;
   }

   /**
    * Get resumes share link
    * @param  integer $resumeid   jobseeker id
    * @param  string  $share_with shared user's id or email
    * @return string   link
    */
   public static function getResumeShareLink($resumeid=0, $share_with='') {
      $db = PFactory::getDbo();
      $query = "SELECT * FROM *PREFIX*share WHERE item_type = 'resumes' AND item_source = ".intval($resumeid)." AND share_with = ".$db->quote($share_with);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $rs = $db->loadAssoc();
      if ( empty($rs) )
         return null;

      return self::getPublicShareLink($rs['item_type'], $rs['token'], $rs['share_with']);
   }

   /**
    * Get event share link
    * @param  integer $eventid    [description]
    * @param  string  $share_with [description]
    * @return [type]              [description]
    */
   public static function getEventShareLink($eventid=0, $share_with='') {
      $db = PFactory::getDbo();
      $query = "SELECT * FROM *PREFIX*share WHERE item_type = 'event' AND item_source = ".intval($eventid)." AND share_with = ".$db->quote($share_with);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $rs = $db->loadAssoc();
      if ( empty($rs) )
         return null;

      return self::getPublicShareLink($rs['item_type'], $rs['token'], $rs['share_with']);
   }

   /**
    * Get public share link
    * @param  string $service    resumes event etc.
    * @param  string $token      share token
    * @param  string $share_with share_with email
    * @return string             return link
    */
   public static function getPublicShareLink($service,$token,$share_with) {
      return OC_Helper::linkToAbsolute( '', 'public.php') . '?service='.$service.'&t='.$token.'&w='.$share_with;
   }

   /**
    * Send offer to jobseeker via email
    * @param  array $user   The email's basic info
    * @return bool
    */
   public static function sendOfferEmail($user, $type=null)
   {
      jimport('joomla.mail.helper');
      if($user && JMailHelper::isEmailAddress($user['email']) && !isFakeEmail($user['email'])){
         require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
         $mailer = new JobmailModelEmail();

         $attachment ='';
         if(!empty($user['attachment']) && !empty($user['company_id']) && !empty($user['file_name'])){
            $filetype = JFile::getExt($user['file_name']);

            $datadir = getUserDataDir($user['company_id']); 
            $extdir = getUserExtDir($user['company_id']);
            $target_path = OC::$SERVERROOT."/data".$datadir."/company/" . $extdir . "/files/offer";

            if(is_file($target_path.'/'.$user['attachment'].'.'.$filetype)) {
               $attachment = $target_path.'/'.$user['attachment'].'.'.$filetype;
            }
         }
         $uploadfilename = (empty($user['file_name']) && !empty($attachment)) ? basename($attachment) : $user['file_name'];

         $msg = ($type == 'copywith')?'(抄送)':'';
         $useremail = ($type == 'copywith')?$user['copywithemail']:$user['email'];

         $config = JFactory::getConfig();
         $supportmail = $config->get('mailfrom','');
         $receiver = (isDevMode() || isTestMode() || isTestUser($user['company_email'])) ? $config->get('jobseekeremail', '') : $useremail;
         $entry_deadline = JHtml::_('date', $user['entry_deadline'], 'Y-m-d H:i');
         $entry_enddate = isNullDate($user['entry_enddate']) ? '': JHTML::_('date', $user['entry_enddate'], 'Y-m-d');
         $offer_link = self::getPublicShareLink('offer',$user['token'],$user['email']);
         $body = '<div class="bs_content_bgimg">
                     <p class="p_text">职位：'.$user['job_title'].'</p>
                     <p class="p_text">入职日期：'.$entry_deadline.'</p>'
                    .(empty($entry_enddate)?'':'<p class="p_text">试用期至：'.$entry_enddate.'</p>').
                    (empty($user['department'])?'':'<p class="p_text">部门：'.$user['department'].'</p>').
                    (empty($user['entrysalary'])?'':'<p class="p_text">试用期月薪：'.$user['entrysalary'].'元</p>').
                    (empty($user['salary'])?'':'<p class="p_text">转正月薪：'.$user['salary'].'元</p>').
                    (empty($user['offer_text'])?'':'<p class="p_text">补充：</p>').
                    '<p class="p_text">'.nl2br($user['offer_text']).'</p>
                  </div>
                  <div style="padding:15px 25px 30px 25px;"> 
                     <a href="'.$offer_link.'&o=accept" style="color:#ffffff; display:inline-block; background:#076c9b; padding:6px 10px; margin-right:10px; font-size:14px;">接受offer</a>
                     <a href="'.$offer_link.'&o=reject" style="color:#ffffff; display:inline-block; background:#989898; padding:6px 10px; font-size:14px;">拒绝offer</a>
                  </div>';

         $mailer->setTemplate('interview_offer'); 
         $mailer->setVariables(array(
            'recipient'=>$receiver,
            'source'=>$user['source'],
            'jobsource'=>$user['jobsource'],
            'fromName'=>'枇杷派云招聘',
            'subject'=>$user['comp_name'].' '.$user['job_title'].'聘用通知书'.$msg,
            'jobseeker'=>$user['jobseekername'],
            'companyname'=>$user['comp_name'],
            'jobtitle'=>$user['job_title'],
            'attachment'=>array(empty($attachment) ? null : array('path'=>$attachment, 'name'=>$uploadfilename)),
            'supportmail'=>$supportmail,
            'hrurl'=>'http://'.OC_Request::serverHost(),
            'body'=>$body
         ));

         $mailer->send();
      }
   }

   /**
    * send email to jobseeker to attend interview
    * @param  array $user   The email's basic info
    * @param  string $type   add or edit
    * @return bool
    */
   public static function sendNotifyEmail($user, $type=null)
   {
      jimport('joomla.mail.helper');
      if($user && JMailHelper::isEmailAddress($user['email']) && !isFakeEmail($user['email'])) {
         require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
         $mailer = new JobmailModelEmail();
         
         $attachment ='';
         if(!empty($user['attachment']) && !empty($user['company_id']) && !empty($user['file_name'])){
            $filetype = JFile::getExt($user['file_name']);

            $datadir = getUserDataDir($user['company_id']); 
            $extdir = getUserExtDir($user['company_id']);
            $target_path = OC::$SERVERROOT."/data".$datadir."/company/" . $extdir . "/files/interview";

            if(is_file($target_path.'/'.$user['attachment'].'.'.$filetype)) {
               $attachment = $target_path.'/'.$user['attachment'].'.'.$filetype;
            }
         }
         $uploadfilename = (empty($user['file_name']) && !empty($attachment)) ? basename($attachment) : $user['file_name'];
         
         $config = JFactory::getConfig();
         $cuser=PFactory::getUser();
         $supportmail = $config->get('mailfrom','');
         $receiver = (isDevMode() || isTestMode() || $cuser->testuser) ? $config->get('jobseekeremail', '') : $user['email'];

         $is_phone = isset($user['is_phone']) ? intval($user['is_phone']) : 0;
         $subject = $is_phone ? '电话' : '';
         $subject .= $type == "edit" ? '面试变动' : '面试邀请';
         $startdate = JHtml::_('date', $user['startdate'], 'Y.m.d H:i');
         $reject_url = OC_Helper::linkToAbsolute( 'index.php/apps/calendar', 'interview') . '?t='.$user['token'].'&e='.$user['email'];
         $body = '<div class="bs_content_bgimg">
                     <p class="p_text">面试时间：'.$startdate.'</p>
                     <p class="p_text">面试地点：'.$user['address'].'</p>
                     <p class="p_text">联系电话：'.$user['contact_phone'].'</p>'.(!empty($user['contact']) ? '<p class="p_text">联系人：'.$user['contact'].'</p>':'')
                     .'<p class="p_text">'.nl2br($user['notify_text']).'</p>
                     </div>
                     <div style="padding:15px 25px 30px 25px;">
                        <a href="'.$reject_url.'" style="text-indent:0em; display:inline-block; padding:0 15px 0 15px; height:40px; line-height:40px; background:#076C9B; color:#ffffff; text-decoration:none; text-align:center;">如您无法参加面试，点击此处</a>
                     </div>';
         if($is_phone == 1){
            if($type == "edit"){
               $mailer->setTemplate('phoneinterview_invite_edit');
            }else{
               $mailer->setTemplate('phoneinterview_invite');
            }
         }else{
            if($type == "edit"){
               $mailer->setTemplate('interview_invite_edit');
            }else{
               $mailer->setTemplate('interview_invite');
            }
         }

         $mailer->setVariables(array(
            'recipient'=>$receiver,
            'source'=>$user['source'],
            'fromName'=>'枇杷派云招聘',
            'subject'=>$user['comp_name'].' '.$user['job_title'].'职位'.$subject,
            'jobseeker'=>$user['jobseekername'],
            'companyname'=>$user['comp_name'],
            'jobtitle'=>$user['job_title'],
            'attachment'=>array(empty($attachment) ? null : array('path'=>$attachment, 'name'=>$uploadfilename)),
            'supportmail'=>$supportmail,
            'hrurl'=>'http://'.OC_Request::serverHost(),
            'body'=>$body
         ));

         $mailer->send();
      }
   }

   /**
    * Function to get user's information
    * @return array user info array
    */
   public static function getUserInformation() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      // Get Email data
      $query = "SELECT f.comp_name, f.contact_name, h.phone,u.email
         FROM #__jobs_employer f
         LEFT JOIN #__comprofiler h ON h.user_id = f.user_id
         LEFT JOIN #__users u ON u.id = f.user_id
         WHERE f.user_id = ".intval($user->id);
      $db->setQuery($query);
      $userinformation = $db->loadAssoc();
      return $userinformation;
   }

   /**
    * send email to interviewer to attend interview
    * @param  array $user   The email's basic info  array $old_datas
    * @param  string $type   add or edit
    * @return bool
    */
   public static function sendInterviewerEventEmail($user, $type=null,$old_datas=null)
   {
      jimport('joomla.mail.helper');
      if($user && JMailHelper::isEmailAddress($user['email'])) {
         // Prepare for attchment and share link
         $vcalendar = $user['vcalendar'];

         $vcalendarname = $user['vcalendarname'];
         $share_link = self::getPublicShareLink('event',$user['token'],$user['email']);

         // Prepare for email send
         require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
         $mailer = new JobmailModelEmail();
         $config = JFactory::getConfig();
         $supportmail = $config->get('mailfrom','');
         $cuser=PFactory::getUser();
         $receiver = (isDevMode() || isTestMode() || $cuser->testuser) ? $config->get('employeremail', '') : $user['email'];
         $is_phone = isset($user['is_phone']) ? intval($user['is_phone']) : 0;
         $phone_event = $is_phone ? '电话' : '';
         $oldphone_event = '';
         if(!empty($old_datas)){
            $oldphone_event = $old_datas['is_phone'] == 1 ? '电话':'';
         }
         $subject =  $type == "edit" ? $oldphone_event.'面试变动': $phone_event.'面试';

         $msg = $type == "edit" ? '您有一个'.$oldphone_event.'面试安排变动' : '您有一个'.$phone_event.'面试安排';

         $plink = $share_link.'&feedback=1';

         $joblink = OC_Helper::linkToAbsolute( '', 'index.php/apps/jobposition/view').'?id='.$user['jobid'];
         $jobseekerlink = PCalendarHelper::getResumeShareLink($user['jobseekerid'], $user['email']);

         $startdate = JHtml::_('date', $user['startdate'], 'Y.m.d H:i');
         $enddate = JHtml::_('date', $user['enddate'], 'H:i');

         $body = '<p class="p1">面试官，您好！<font style="color:#ff6600;">'.$msg.'</font></p>
                  <p class="p2" style="color:#408e20;"><b>此邮件系统发出，请勿直接回复，如有问题请直接联系HR。</b></p>
                  <p class="p3"><b>职位名称：</b><a href="'.$joblink.'">'.$user['job_title'].'</a></p>
                  <p class="p3"><b>应&nbsp;&nbsp;聘&nbsp;&nbsp;者：</b><a href="'.$jobseekerlink.'">'.$user['jobseekername'].'</a></p>';
         $body .= $is_phone ? '<p class="p3"><b>应聘者电话：</b>'.$user['phone'].'</p>' : '';

         if(!empty($old_datas)){
            $old_event = $old_datas['is_phone'] == 1 ? '电话':'';
            $old_startdate = JHtml::_('date', $old_datas['startdate'], 'Y.m.d H:i');
            $old_enddate = JHtml::_('date', $old_datas['enddate'], 'Y.m.d H:i');
            $old_summary = $old_datas['summary'];
            $body .=' <p class="p3"><b style="color:#ff6600;">原定：</b></p>
                      <p class="p3"><b>'.$old_event.'面试</b></p>
                      <p class="p3"><b>面试时间：</b>'.$old_startdate.' 至 '.$old_enddate.'</p>' .
                      ( empty($old_summary) ? '' : '<p class="p3"><b>备注：</b>'. nl2br($old_summary) .'</p> ' ) .
                      ' <p class="p3"><b style="color:#ff6600;">更改为：</b></p>
                      <p class="p3"><b>'.$phone_event.'面试</b></p>
                      <p class="p3"><b>面试时间：</b>'.$startdate.' 至 '.$enddate.'</p>' .
                      ( empty($user['summary']) ? '' : '<p class="p3"><b>备注：</b>' . nl2br($user['summary'])  . '</p> '); 

         }else{
            $body .='<p class="p3"><b>面试时间：</b>'.$startdate.' 至 '.$enddate.'</p>' . 
                     ( empty($user['summary']) ? '' : '<p class="p3"><b>面试备注：</b></p><p class="p3">'.nl2br($user['summary']).'</p>');
         }
         $body .='<div>
                     <a href="'.$share_link.'" style="color:#ffffff; display:inline-block; background:#076c9b; padding:6px 10px; margin-right:10px; font-size:14px;">查看面试详情</a>
                     <a href="'.$plink.'" style="color:#ffffff; display:inline-block; background:#076c9b; padding:6px 10px; margin-right:10px; font-size:14px;">写反馈</a>
                     <a href="'.$plink.'&absent=1" style="color:#ffffff; display:inline-block; background:#989898; margin-right:10px; padding:6px 10px; font-size:14px;">应聘者缺席</a>
                     <a href="'.$plink.'&notattended=1" style="color:#ffffff; display:inline-block; background:#989898; padding:6px 10px; font-size:14px;">我未参加面试</a>
                  </div>';

         $mailer->setTemplate('interviewer');
         $mailer->setVariables(array(
            'recipient'=>$receiver,
            'source'=>$user['source'],
            'jobsource'=>$user['jobsource'],
            'fromName'=>'枇杷派云招聘',
            'subject'=>$subject.'：'.$user['job_title'].$user['jobseekername'].' '.$startdate,
            'attachment'=>array(array('string'=>$vcalendar, 'filename'=>$vcalendarname)),
            'supportmail'=>$supportmail,
            'hrurl'=>'http://'.OC_Request::serverHost(),
            'body'=>$body
         ));

         $mailer->send();
      }
   }

   /**
    * send email to interview to feedback
    * @param array $user  The email's basic info
    * @return bool
    */
   public static function sendFeedbackRemindEmail($user){
      jimport('joomla.mail.helper');
      if($user && JMailHelper::isEmailAddress($user['email'])) {
         // Prepare for attchment and share link
         $vcalendar = $user['vcalendar'];
         $vcalendarname = $user['vcalendarname'];
         $share_link = self::getPublicShareLink('event',$user['token'],$user['email']);

         // Prepare for email send
         require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
         $mailer = new JobmailModelEmail();
         $config = JFactory::getConfig();
         $supportmail = $config->get('mailfrom','');
         $cuser=PFactory::getUser();
         $receiver = (isDevMode() || isTestMode() || $cuser->testuser) ? $config->get('employeremail', '') : $user['email'];
         $subject = '您有一个面试反馈尚未完成，请您尽快做出反馈！';
         $plink = $share_link.'&feedback=1';
         $startdate = JHtml::_('date', $user['startdate'], 'Y.m.d H:i');
         $enddate = JHtml::_('date', $user['enddate'], 'H:i');

         $body = '<p class="p1">面试官，您好！<font style="color:#ff6600;">'.$subject.'</font></p>
                  <p class="p2" style="color:#408e20;"><b>此邮件系统发出，请勿直接回复，如有问题请直接联系HR。</b></p>
                  <p class="p3"><b>职位名称：</b>'.$user['job_title'].'</p>
                  <p class="p3"><b>应&nbsp;&nbsp;聘&nbsp;&nbsp;者：</b>'.$user['jobseekername'].'</p>
                  <p class="p3"><b>面试时间：</b>'.$startdate.' - '.$enddate.'</p>
                  <p class="p3"><b>面试备注：</b>'.( empty($user['summary']) ? "暂无备注" : "" ).'</p>'
                  .( !empty($user['summary']) ? '<p class="p3">'.nl2br($user['summary']).'</p>' : "" )

                  .'<p class="p3">
                     <a href="'.$plink.'" style="color:#ffffff; display:inline-block; background:#076c9b; padding:6px 10px; margin-right:10px; font-size:14px;">面试反馈表</a>
                     <a href="'.$plink.'&absent=1" style="color:#ffffff; display:inline-block; background:#989898; padding:6px 10px; margin-right:10px; font-size:14px;">应聘者缺席</a>
                     <a href="'.$plink.'&notattended=1" style="color:#ffffff; display:inline-block; background:#989898; padding:6px 10px; margin-right:10px; font-size:14px;">我未参加面试</a>
                  </p>
                  <p class="p3 p4" style="margin-top:15px;">如无法点击，请将链接拷贝至浏览器地址栏直接访问。</p>'.
                  '<a href="' . $plink . '">' . $plink . '</a>';

         $mailer->setTemplate('interviewer');
         $mailer->setVariables(array(
            'recipient'=>$receiver,
            'source'=>$user['source'],
            'jobsource'=>$user['jobsource'],
            'fromName'=>'枇杷派云招聘',
            'subject'=>'面试反馈提醒：'.$user['job_title'].$user['jobseekername'],
            'attachment'=>array(array('string'=>$vcalendar, 'filename'=>$vcalendarname)),
            'supportmail'=>$supportmail,
            'hrurl'=>'http://'.OC_Request::serverHost(),
            'body'=>$body
         ));

         $mailer->send();
      }
   }

   /**
    * send email to interviewer or interviewcreater to cancel interview
    * @param  array $user   The email's basic info
    * @param  string $type interviewer interviewcreater
    * @return bool
    */
   public static function sendInterviewCancelEmail($user,$type=null)
   {
      jimport('joomla.mail.helper');
      if($user && JMailHelper::isEmailAddress($user['email']) && !isFakeEmail($user['email'])){
         require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
         $mailer = new JobmailModelEmail();
         $config = JFactory::getConfig();
         $supportmail = $config->get('mailfrom','');
         $cuser=PFactory::getUser();
         $receiver = (isDevMode() || isTestMode() || $cuser->testuser) ? $config->get('employeremail', '') : $user['email'];
         $is_phone = $user['is_phone'] == 1 ?'电话':'';
         $msg = $type == 'creater' ? '应聘者无法参加面试':'您的'.$is_phone.'面试安排已被取消';
         $startdate = JHtml::_('date', $user['startdate'], 'Y.m.d H:i');
         $enddate = JHtml::_('date', $user['enddate'], 'H:i');
         $joblink = OC_Helper::linkToAbsolute( '', 'index.php/apps/jobposition/view').'?id='.$user['jobid'];
         $jobseekerlink = PCalendarHelper::getResumeShareLink($user['jobseekerid'], $user['email']);
         if($type == 'creater'){
            $subject = '无法参加'.$is_phone.'面试，';
            $body = '<p class="p1">尊敬的用户，您好！<font style="color:#ff6600;">应聘者无法参加'.$is_phone.'面试</font></p>
                     <p class="p2" style="color:#408e20;"><b>此邮件系统发出，请勿直接回复，如有问题请直接联系HR。</b></p>
                     <p class="p3"><b>职位名称：</b><a href="'.$joblink.'">'.$user['job_title'].'</a></p>
                     <p class="p3"><b>应&nbsp;&nbsp;聘&nbsp;&nbsp;者：</b><a href="'.$jobseekerlink.'">'.$user['jobseekername'].'</a></p>
                     <p class="p3"><b>原定面试时间：</b>'.$startdate.' 至 '.$enddate.'</p>
                     <p class="p3"><b>原因：</b>'.$user['reason'].'</p>';
         }else{
            $subject = $is_phone.'面试取消：';
            $body = '<p class="p1">面试官，您好！<font style="color:#ff6600;">'.$msg.'</font></p>
                     <p class="p2" style="color:#408e20;"><b>此邮件系统发出，请勿直接回复，如有问题请直接联系HR。</b></p>
                     <p class="p3"><b>职位名称：</b><a href="'.$joblink.'">'.$user['job_title'].'</a></p>
                     <p class="p3"><b>应&nbsp;&nbsp;聘&nbsp;&nbsp;者：</b><a href="'.$jobseekerlink.'">'.$user['jobseekername'].'</a></p>
                     <p class="p3"><b>面试时间：</b>'.$startdate.' - '.$enddate.'</p>';
         }

         $mailer->setTemplate('interviewer_cancel');
         $mailer->setVariables(array(
            'recipient'=>$receiver,
            'fromName'=>'枇杷派云招聘',
            'source'=>$user['source'],
            'jobsource'=>$user['jobsource'],
            'subject'=>$subject.$user['job_title'].$user['jobseekername'],
            'is_phone'=>$is_phone,
            'supportmail'=>$supportmail,
            'hrurl'=>'http://'.OC_Request::serverHost(),
            'body'=>$body
         ));

         $mailer->send();
      }
   }

   /**
    * send cancel interview email to jobseeker
    * @param  array $user   The email's basic info
    * @return bool
    */
   public static function sendJobseekerCancelEmail($user)
   {
      jimport('joomla.mail.helper');
      if($user && JMailHelper::isEmailAddress($user['email']) && !isFakeEmail($user['email'])){
         require_once JPATH_SITE.'/components/com_jobmail/models/email.php';
         $mailer = new JobmailModelEmail();
         $config = JFactory::getConfig();
         $supportmail = $config->get('mailfrom','');
         $receiver = (isDevMode() || isTestMode() || isTestUser($user['company_email'])) ? $config->get('employeremail', '') : $user['email'];
         $is_phone = $user['is_phone'] == 1 ?'电话':'';

         $subject = $is_phone.'面试取消';
         $interviewdate = JHtml::_('date', $user['startdate'], 'Y-m-d');
         $interviewtime = JHtml::_('date', $user['startdate'], 'H:i');

         $mailer->setTemplate('jobseeker_cancel');
         $mailer->setVariables(array(
            'recipient'=>$receiver,
            'source'=>$user['source'],
            'jobsource'=>$user['jobsource'],
            'fromName'=>'枇杷派云招聘',
            'subject'=>$user['comp_name'].' '.$user['job_title'].'职位'.$subject,
            'is_phone'=>$is_phone,
            'interviewdate'=>$interviewdate,
            'interviewtime'=>$interviewtime,
            'companyname'=>$user['comp_name'],
            'jobseeker'=>$user['jobseekername'],
            'jobtitle'=>$user['job_title'],
            'supportmail'=>$supportmail,
            'hrurl'=>'http://'.OC_Request::serverHost()
         ));

         $mailer->send();
      }
   }

   /**
    * Get Interviewers Email Data From Parentid
    * @param  int $parentid parent object id
    * @return user assoc list array
    */
   public static function getInterviewerEmailDataFromParentid($parentid) {
      $db = PFactory::getDbo();
      $query = "SELECT a.objectid,a.jobseekerid, c.summary, c.round, a.uid AS email, b.startdate, b.enddate, b.calendardata AS vcalendar, b.uri AS vcalendarname, a.jobseekername, c.jobid, d.job_title, d.source as jobsource, e.token, c.is_phone, f.phone, f.source
         FROM *PREFIX*calendar_interview_events a
         LEFT JOIN *PREFIX*calendar_objects b ON b.id = a.objectid
         LEFT JOIN *PREFIX*calendar_objects_details c ON c.objectid = ".intval($parentid)."
         LEFT JOIN #__jobs_job d ON d.id = c.jobid
         LEFT JOIN *PREFIX*share e ON e.share_with = a.uid AND e.item_source = a.objectid
         LEFT JOIN *PREFIX*hr_jobseeker f ON f.id = a.jobseekerid
         WHERE a.parent = ".intval($parentid)." AND a.objectid <>".intval($parentid);
      // Try to load from cache
      $cache = CacheHelper::getCache('app_calendar');
      // Get cached data now
      $users = $cache->call(array('PCalendarHelper', '_getInterviewerEmailDataFromParentid'), $query);
      // Event Driven Cache/Object Caching
      if ($users) {
         CacheHelper::setTriggers(PFactory::getMasterUser()->get('id'), $cache, array('*PREFIX*calendar_interview_events-'.$parentid, '*PREFIX*calendar_objects-'.$parentid,'*PREFIX*calendar_objects_details-'.$parentid,'#__jobs_job','*PREFIX*share'));
      } else {
         // Don't cache null data
         $cache->removeCache(array('PCalendarHelper', '_getInterviewerEmailDataFromParentid'), $query);
      }

      return $users;
   }

   public static function _getInterviewerEmailDataFromParentid($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList();
   }

   /**
    * Get Single Interviewer Email Data From Objectid
    * @param  int $parentid parent object id
    * @return user assoc array
    */
   public static function getInterviewerEmailDataFromObjectid($objectid,$master_uid=null) {
      $master_uid = empty($master_uid) ? PFactory::getMasterUser()->get('id') : intval($master_uid); 
      $db = PFactory::getDbo();
      $query = "SELECT a.uid AS email, a.parent,a.eventtype, a.objectid, c.round, c.summary, a.jobseekerid, b.startdate, b.enddate, b.calendardata AS vcalendar, b.uri AS vcalendarname, a.jobseekername, c.jobid, d.source as jobsource, d.job_title, e.token, c.is_phone, f.phone, f.source
         FROM *PREFIX*calendar_interview_events a
         LEFT JOIN *PREFIX*calendar_objects b ON b.id = a.objectid
         LEFT JOIN *PREFIX*calendar_objects_details c ON c.objectid = a.parent
         LEFT JOIN #__jobs_job d ON d.id = c.jobid
         LEFT JOIN *PREFIX*share e ON e.share_with = a.uid AND e.item_source = a.objectid
         LEFT JOIN *PREFIX*hr_jobseeker f ON f.id = a.jobseekerid
         WHERE a.objectid = ".intval($objectid) . " AND f.company_id=". $master_uid;
      // Try to load from cache
      $cache = CacheHelper::getCache('app_calendar');
      // Get cached data now
      $user = $cache->call(array('PCalendarHelper', '_getInterviewerEmailDataFromObjectid'), $query);

      //$master_uid = empty(PFactory::getMasterUser()->get('id'))? $master_uid : PFactory::getMasterUser()->get('id');
      // Event Driven Cache/Object Caching
      if ($user) {
         CacheHelper::setTriggers($master_uid, $cache, array('*PREFIX*calendar_interview_events-'.$user['parent'], '*PREFIX*calendar_objects-'.$user['parent'],'*PREFIX*calendar_objects_details-'.$user['parent'],'#__jobs_job','*PREFIX*share'));
      } else {
         // Don't cache null data
         $cache->removeCache(array('PCalendarHelper', '_getInterviewerEmailDataFromObjectid'), $query);
      }

      return $user;
   }

   public static function _getInterviewerEmailDataFromObjectid($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssoc();
   }

   /**
    * Get Interviewer displayname From Objectid
    * @param  int $objectid
    * @return interviewer result
    */
   public static function getInterviewerNameFromObjectid($objectid) {
      $db = PFactory::getDbo();
      $query = "SELECT GROUP_CONCAT(IF(displayname IS NOT NULL AND length(displayname)>0, displayname, uid)) AS interviewers
         FROM *PREFIX*calendar_interview_events
         WHERE objectid = ".intval($objectid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $interviewer = $db->loadResult();
      return $interviewer;
   }

   /**
    * Get Feedbackinfo From Objectid
    * @param  int $objectid $companyid
    * @return Feedbackinfo result
    */
   public static function getFeedbackinfoFromObjectid($objectid,$companyid) {
      $db = PFactory::getDbo();

      $query = "SELECT IF(fa.displayname IS NOT NULL AND length(fa.displayname)>0, fa.displayname, fa.userid) AS interviewer, ie.uid AS uid, fa.checkpoints, fa.suggestion_id, fa.comment, fa.round, ie.jobseekername, jj.job_title, co.startdate, od.jobid, ie.jobseekerid, ie.parent
         FROM *PREFIX*calendar_feedback_answer AS fa
         LEFT JOIN *PREFIX*calendar_interview_events AS ie ON ie.objectid = fa.objectid
         LEFT JOIN *PREFIX*calendar_objects AS co ON co.id = fa.objectid
         LEFT JOIN *PREFIX*calendar_objects_details AS od ON od.objectid = ie.parent
         LEFT JOIN #__jobs_job AS jj ON jj.id = od.jobid
         WHERE fa.objectid = ".intval($objectid)." AND jj.employer_id = ".intval($companyid);
      // Try to load from cache
      $cache = CacheHelper::getCache('app_calendar');
      // Get cached data now
      $feedbackinfo = $cache->call(array('PCalendarHelper', '_getFeedbackinfoFromObjectid'), $query);
      // Event Driven Cache/Object Caching
      if ($feedbackinfo) {
         CacheHelper::setTriggers($companyid, $cache, array('*PREFIX*calendar_feedback_answer-'.$feedbackinfo['parent'], '*PREFIX*calendar_interview_events-'.$feedbackinfo['parent'],'*PREFIX*calendar_objects-'.$feedbackinfo['parent'],'*PREFIX*calendar_objects_details-'.$feedbackinfo['parent'],'#__jobs_job'));
      } else {
         // Don't cache null data
         $cache->removeCache(array('PCalendarHelper', '_getFeedbackinfoFromObjectid'), $query);
      }

      return $feedbackinfo;
   }

   public static function _getFeedbackinfoFromObjectid($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssoc();
   }

   /**
    * Get subaccounts userid
    * @return array
    */
   public static function getSubaccounts() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT GROUP_CONCAT(uid)
         FROM *PREFIX*users_extended
         WHERE deleted=0 AND owner = " . intval($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));

      $result = $db->loadResult();
      if ( !empty($result) ) {
         $accounts = explode(',', $result);
         return $accounts;
      }
      return array();
   }

   /**
    * Get all calender IDs by master userid, include subaccount's calendar ID
    * @return array
    */
   public static function getAllCalID() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT GROUP_CONCAT(DISTINCT a.id) AS calids
         FROM *PREFIX*calendar_calendars a
         LEFT JOIN *PREFIX*users_extended b ON b.uid = a.userid
         WHERE a.userid = ".intval($user->id)." OR b.owner = ".intval($user->id);
      $db->setQuery(PUtil::replaceOCPrefix($query));

      $result = $db->loadResult();
      if ( !empty($result) ) {
         $calids = explode(',', $result);
         return $calids;
      }
      return array();
   }

   /**
    * Get last round time by objectid
    * @return $lastroundtime
    */
   public static function getLastRoundTimeByObjectid($objectid,$round) {
      $db = PFactory::getDbo();
      if($round > 0){
         $query = "SELECT enddate FROM *PREFIX*calendar_objects WHERE id = ".intval($objectid);
      }else{
         $query = "SELECT a.enddate
            FROM *PREFIX*calendar_objects a
            LEFT JOIN *PREFIX*calendar_interview_events e ON e.objectid= a.id
            WHERE e.next = ".intval($objectid);
      }
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $lastroundtime = $db->loadResult();
      return $lastroundtime;
   }
   
   public static function sendSMSMessage($user,$smstpl='jobappl'){
      if ( $user && $smstpl ) {
         // load sms helper
         require_once(JPATH_SITE.'/components/com_jobmail/helpers/sms.php');
         require_once(JPATH_SITE.'/components/com_support/helper.php');
         $smshelper = SmsHelper::sendSingleCustomSMS($user, $smstpl);
      }
   }

   public static function checkSendOfferDate($posttime,$jobseekerid){
      if(empty($posttime) && empty($jobseekerid)){
         return false;
      }

      $db = PFactory::getDbo();
      $config = PFactory::getConfig();
      $posttime = JFactory::getDate($posttime, $config->get("offset"));

      $query = "SELECT co.startdate FROM *PREFIX*calendar_interview_result cir LEFT JOIN *PREFIX*calendar_objects co ON co.id = cir.last_interview_objectid WHERE cir.jobseekerid = ".intval($jobseekerid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $startdate = $db->loadResult();
      $startdate = JFactory::getDate($startdate);
      if($posttime->toUnix() <= $startdate->toUnix()){
         return false;
      }

      return true; 
   }

   public static function updateNumEvent() {
      $master = PFactory::getMasterUser(); 
      $db = PFactory::getDbo(); 

      $query = "UPDATE #__jobs_employer AS a SET a.num_calendarevents = (
               SELECT count(*)
               FROM *PREFIX*calendar_objects_details cod 
               LEFT JOIN *PREFIX*calendar_objects co ON cod.objectid = co.id 
               LEFT JOIN *PREFIX*calendar_calendars cc ON co.calendarid = cc.id 
               LEFT JOIN *PREFIX*users_extended ue ON cc.userid = ue.uid  
               WHERE (cc.userid = CAST(a.user_id AS char(11))  OR ue.owner = a.user_id )) 
               WHERE a.user_id = " . intval($master->id);

      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
   }

}

